﻿using System;
using Microsoft.SharePoint;
using RoketSolutions.SP2010.Infrostructure.Common.Extensions;

namespace RoketSolutions.SP2010.Infrostructure.Data.Entities
{
    [Serializable]
    public abstract class ListEntityBase
    {
        public SPListItem Item { get; set; }

        protected ListEntityBase(SPListItem item)
        {
            Item = item;
        }

        public int Id
        {
            get
            {
                return Item.ID;
            }
        }

        public virtual string Title
        {
            get
            {
                return Item.Title;
            }
            set
            {
                Item["Title"] = value;
            }
        }

        public SPUser Editor
        {
            get { return Item.GetUser("Editor"); }
        }

        public DateTime Created
        {
            get
            {
                var created = Item.GetNullableDateTime("Created");
                return created != null ? created.Value : DateTime.Now;
            }
        }

        public DateTime Modified
        {
            get
            {
                var modified = Item.GetNullableDateTime("Modified");
                return modified != null ? modified.Value : DateTime.Now;
            }
        }

        public bool IsNew
        {
            get
            {
                var daysToShowNew = Item.Web.Site.WebApplication.DaysToShowNewIndicator;
                var daysPassed = DateTime.Now.Subtract(Created).Days;
                return daysToShowNew > daysPassed;
            }
        }

        public string CreatedShortDate
        {
            get
            {
                return Created.ToShortDateString();
            }
        }

        public void Update()
        {
            bool allowUnsafeUpdates = Item.Web.AllowUnsafeUpdates;
            try
            {
                Item.Web.AllowUnsafeUpdates = true;
                Item.Update();
            }
            finally
            {
                Item.Web.AllowUnsafeUpdates = allowUnsafeUpdates;
            }
        }

        public void Update(bool changeVersion)
        {
            bool allowUnsafeUpdates = Item.Web.AllowUnsafeUpdates;
            try
            {
                Item.Web.AllowUnsafeUpdates = true;
                Item.SystemUpdate(changeVersion);
            }
            finally
            {
                Item.Web.AllowUnsafeUpdates = allowUnsafeUpdates;
            }
        }
    }

}